package com.clwl.supervise.superviseapp.service.inspect;


import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.clwl.supervise.superviseapp.entity.base.*;
import com.clwl.supervise.superviseapp.entity.risk.JgPointDistance;
import com.clwl.supervise.superviseapp.entity.supervise.*;
import com.clwl.supervise.superviseapp.mapper.base.JgProcessCodeMapper;
import com.clwl.supervise.superviseapp.mapper.base.TcCompanyMapper;
import com.clwl.supervise.superviseapp.mapper.base.TsDeptMapper;
import com.clwl.supervise.superviseapp.mapper.base.TsUserMapper;
import com.clwl.supervise.superviseapp.mapper.risk.JgRiskCheckContentMapper;
import com.clwl.supervise.superviseapp.mapper.supervise.*;
import com.clwl.supervise.superviseapp.service.SequenceService;
import com.clwl.supervise.superviseapp.service.base.BaseDataService;
import com.clwl.supervise.superviseapp.util.UserHelper;
import com.clwl.supervise.superviseapp.util.file.FileResultEntity;
import com.clwl.supervise.superviseapp.util.file.FileUploadEnum;
import com.clwl.supervise.superviseapp.util.file.FileUploadUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;


@Slf4j
@Service(value = "SchemePlanService")
public class SchemePlanService {


    @Resource
    private JgProcessCodeMapper jgProcessCodeMapper;

    @Resource
    private JgClassifySpxsMapper classifySpxsMapper;
    @Resource
    private JgClassifyCyfwMapper classifyCyfwMapper;
    @Resource
    private JgClassifySpscCompMapper classifySpscCompMapper;
    @Resource
    private TsUserMapper userMapper;
    @Resource
    private JgCheckMissingMapper checkMissingMapper;
    @Resource
    private JgCheckProblemMapper checkProblemMapper;
    @Resource
    private JgStandardMapper jgStandardMapper;
    @Resource
    private JgCheckContentMapper checkContentMapper;
    @Resource
    private JgFlightPlanCheckMapper flightPlanCheckMapper;
    @Resource
    private JgSchemePlanCheckMapper schemePlanCheckMapper;
    @Resource
    private JgSchemePlanUserMapper schemePlanUserMapper;
    @Resource
    private JgSchemeStandardMapper schemeStandardMapper;
    @Resource
    private JgSchemeContentFileMapper contentFileMapper;
    @Resource
    private JgSchemeContentMapper schemeContentMapper;
    @Resource
    private JgDailyStandardMapper dailyStandardMapper;
    @Resource
    private JgDailyContentMapper dailyContentMapper;
    @Resource
    private JgCheckGuideMapper checkGuideMapper;

    @Resource
    private TcCompanyMapper tcCompanyMapper;
    @Resource
    private JsEntAnomalyMapper jsEntAnomalyMapper;

    @Resource
    private JgRectificationMapper rectificationMapper;


    @Resource
    private JgRectificationContentMapper rectificationContentMapper;

    @Resource
    private JgInvestigationMapper investigationMapper;

    @Resource
    private JgInvestigationSetMapper investigationSetMapper;

    @Resource
    private JgInvestigationContentMapper investigationContentMapper;

    @Resource
    private JgScDynamicScoringMapper scDynamicScoringMapper;

    @Resource
    private JgDailyCheckMapper dailyCheckMapper;

    @Resource
    private DailyInspectService dailyInspectService;


    @Resource
    private JgRiskCheckContentMapper riskCheckContentMapper;

    @Resource
    private BaseDataService baseDataService;


    @Resource
    private TsDeptMapper tsDeptMapper;


    @Resource
    private SequenceService sequenceService;

    @Resource
    private JgCheckContentMapper jgCheckContentMapper;


    public IPage<Map<String, Object>> selectCompanyPage(Integer pageNum, Integer pageSize, CommonSearchEntity params) {

        params.setCreatorId(UserHelper.getUserId());
        String dataRange = UserHelper.getUserInfo().getDataRange();
        params.setUserId(UserHelper.getUserId());
        params.setDataRange(dataRange);
        params.setDeptId(UserHelper.getUserInfo().getDeptId());
        params.setBusinessFormatRange(UserHelper.getUserInfo().getBusinessFormatRange());
        String deptType = "3";
        if ("0".equals(dataRange)) {
            deptType = "0";
        } else if ("1".equals(dataRange)) {
            deptType = "1";
        } else if ("2".equals(dataRange)) {
            deptType = "2";
        } else if ("3".equals(dataRange)) {
            deptType = "2";
        }
        TsDept dataDeptEntity = tsDeptMapper.getDataParentDeptId(UserHelper.getUserInfo().getDeptId(), deptType);
        if (dataDeptEntity != null) {
            params.setDataDeptId(dataDeptEntity.getId());
        } else {
            params.setDataDeptId(UserHelper.getUserInfo().getDeptId());
        }
        if (UserHelper.getUserInfo().getBusinessFormatRange().indexOf("2") >= 0 || UserHelper.getUserInfo().getBusinessFormatRange().indexOf("3") >= 0) {
            params.setIsSc("1");
        } else {
            params.setIsSc("0");
        }
        Page<Map<String, Object>> iPage = Page.of(pageNum, pageSize);
        //iPage.setOptimizeCountSql(false);
        //iPage.setSearchCount(false);
        log.info("type:{}", params.getType());
        if ("0".equals(params.getType())) {
            //待检查
            return schemePlanCheckMapper.selectCompanyList(iPage, params);
        } else {
            //已检查
            return schemePlanCheckMapper.selectCheckResult(iPage, params);
        }
    }

    /**
     * 获取检查时候的显示信息
     *
     * @param checkId 检查单id
     * @return
     */
    public JgSchemePlanCheck getSchemeCheckInfo(Long checkId) {
        JgSchemePlanCheck schemePlanCheck = schemePlanCheckMapper.selectById(checkId);
        schemePlanCheck.setManageStatus(schemePlanCheck.getManageStatus() == null ? "0" : schemePlanCheck.getManageStatus());
        schemePlanCheck.setDelayCheck(schemePlanCheck.getDelayCheck() == null ? "0" : schemePlanCheck.getDelayCheck());
        schemePlanCheck.setVerificationRecords("");
        TcCompany company = tcCompanyMapper.selectById(schemePlanCheck.getCompanyId());
        schemePlanCheck.setSuperviseDeptName(company.getDeptName());
        JgPointDistance distance = baseDataService.getCheckDistance(schemePlanCheck.getCompanyId() + "");
        schemePlanCheck.setDistance(distance.getDistance());
        List<JgSchemePlanUser> schemePlanUser = schemePlanUserMapper.selectByPlanId(schemePlanCheck.getPlantId());
        schemePlanCheck.setSchemePlanUserList(schemePlanUser);
        schemePlanCheck.setLngLat(company.getLngLat());
        schemePlanCheck.setCompanyAddress(company.getAddress());
        //给个默认的页面好显示
        if (schemePlanCheck.getProcessResults() == null) {
            schemePlanCheck.setProcessResults("1");
        }
        //获取企业的一级业态信息
        if (company.getSupProcess() != null) {
            JgProcessCode processCode = jgProcessCodeMapper.selectByCode(company.getSupProcess());
            schemePlanCheck.setCompanyTypeName(processCode.getName());
            switch (company.getSupProcess()) {
                case "spxs":
                    JgClassifySpxs classifySpxs = classifySpxsMapper.selectByProcessCodeAndCompanyType(processCode.getId(), company.getCompanyTypeId());
                    schemePlanCheck.setCompanyTypeName(schemePlanCheck.getCompanyTypeName() + (classifySpxs == null ? "" : "/" + classifySpxs.getName()));
                    break;
                case "cyfw":
                    JgClassifyCyfw classifyCyfw = classifyCyfwMapper.selectByProcessCodeAndCompanyType(processCode.getId(), company.getCompanyTypeId());
                    schemePlanCheck.setCompanyTypeName(schemePlanCheck.getCompanyTypeName() + (classifyCyfw == null ? "" : "/" + classifyCyfw.getName()));
                    break;
                case "spsc":
                    Map<String, Object> classifysc = classifySpscCompMapper.selectByCompanyId(company.getId(), processCode.getId(), "1", "0");
                    schemePlanCheck.setCompanyTypeName(schemePlanCheck.getCompanyTypeName() + (classifysc == null ? "" : "/" + classifysc.get("NAME").toString()));
                    break;
                case "tssc":
                    Map<String, Object> classifyts = classifySpscCompMapper.selectByCompanyId(company.getId(), processCode.getId(), "1", "1");
                    schemePlanCheck.setCompanyTypeName(schemePlanCheck.getCompanyTypeName() + (classifyts == null ? "" : "/" + classifyts.get("NAME").toString()));
                    break;
            }
        }
        schemePlanCheck.setCompanyNatureBusiness(company.getBusinessScope());
        schemePlanCheck.setCompanyContact(company.getContact());
        schemePlanCheck.setCompanyContactPhone(company.getContactPhone());
        schemePlanCheck.setSupProcess(company.getSupProcess());

        if (schemePlanCheck.getTemplateId() == null) {
            throw new RuntimeException("检查任务的模板未选择，请再电脑端进行选择!");
        }
        //查看当前企业是否之前填写了检查信息
        try {
            //获取已经填写的检查内容
            //风险信息
            Map<String, String> riskMap = baseDataService.riskInfo(company.getId());
            List<String> riskCode = new ArrayList<>();
            Set<String> riskKeySet = riskMap.keySet();
            for (String riskKey : riskKeySet) {
                if (!riskMap.get(riskKey).equals("0")) {
                    riskCode.add(riskKey);
                }
            }
            //标准列表
            List<JgStandard> checkStandardList = jgStandardMapper.getStanardByTemplateId(schemePlanCheck.getTemplateId());
            ArrayList<JgSchemeStandard> schemeStandardList = new ArrayList<>();
            List<Map<String, Object>> checkMissingListAll = checkMissingMapper.selectMapList();
            List<Map<String, Object>> checkProblemListAll = checkProblemMapper.selectMapList();
            for (JgStandard standard : checkStandardList) {
                JgSchemeStandard schemeStandard = schemeStandardMapper.selectByStandardId(schemePlanCheck.getId(), standard.getId());
                if (schemeStandard == null) {
                    schemeStandard = new JgSchemeStandard();
                    schemeStandard.setCreateTime(new Date());
                    schemeStandard.setCreatorId(UserHelper.getUserId());
                    schemeStandard.setCreator(UserHelper.getUserInfo().getName());
                    schemeStandard.setCreateDeptId(UserHelper.getUserInfo().getDeptId());
                    schemeStandard.setCreateDeptName(UserHelper.getUserInfo().getDeptName());
                    schemeStandard.setSchemePlanCheckId(schemePlanCheck.getId());
                    schemeStandard.setDeleteFlag(0);
                    schemeStandard.setTemplateId(standard.getTemplateId());
                    schemeStandard.setStandardId(standard.getId());
                    schemeStandard.setSupCategory(standard.getSupCategory());
                    schemeStandard.setSupProcess(standard.getSupProcess());
                    schemeStandard.setSpxsId(standard.getSpxsId());
                    schemeStandard.setCyfwId(standard.getCyfwId());
                    schemeStandard.setSpscLbId(standard.getSpscLbId());
                    schemeStandard.setSpscLbZlId(standard.getSpscLbZlId());
                    schemeStandard.setTsspLbId(standard.getTsspLbId());
                    schemeStandard.setTsspLbZlId(standard.getTsspLbZlId());
                    schemeStandard.setName(standard.getName());
                    schemeStandard.setSerialNum(standard.getSerialNum());
                    schemeStandardMapper.insert(schemeStandard);
                }
//                List<JgSchemeContent>  realySchemeContentList = schemeContentMapper.selectByStandardId(schemeStandard.getId());
                List<JgCheckContent> checkContentList = checkContentMapper.selectEntityByStandardId(standard.getId());
                List<JgSchemeContent> schemeContentList = new ArrayList<>();
                for (JgCheckContent jgCheckContent : checkContentList) {
                    JgSchemeContent schemeContent = schemeContentMapper.selectByStandardIdAndCheckContendId(schemeStandard.getId(), jgCheckContent.getId(), riskCode);
                    if (schemeContent == null) {
                        schemeContent = new JgSchemeContent();
                        schemeContent.setContentId(jgCheckContent.getId());
                        schemeContent.setSchemeStandardId(schemeStandard.getId());
                        schemeContent.setCheckContent(jgCheckContent.getCheckContent());
                        schemeContent.setImportentItem(jgCheckContent.getImportentItem());
                        schemeContent.setMissingItem(jgCheckContent.getMissingItem());
                        schemeContent.setRemark(jgCheckContent.getRemark());
                        schemeContent.setScore(jgCheckContent.getScore());
                        schemeContent.setSerialNum(jgCheckContent.getSerialNum());
                        schemeContent.setCreateTime(new Date());
                        schemeContent.setCreatorId(UserHelper.getUserId());
                        schemeContent.setCreator(UserHelper.getUserInfo().getName());
                        schemeContent.setCreateDeptId(UserHelper.getUserInfo().getDeptId());
                        schemeContent.setCreateDeptName(UserHelper.getUserInfo().getDeptName());
                        schemeContent.setDeleteFlag(0);
                        try {
                            int riskCount = riskCheckContentMapper.selectCountByCheckContent(jgCheckContent.getId(), riskCode);
                            schemeContent.setRiskCount(riskCount);
                        } catch (Exception e) {
                            schemeContent.setRiskCount(0);
                        }
                        JgCheckGuide checkGuide = checkGuideMapper.selectByContentId(jgCheckContent.getId());
                        if (checkGuide != null) {
                            schemeContent.setCheckBasis(checkGuide.getCheckBasis());
                            schemeContent.setCheckMethod(checkGuide.getCheckMethod());
                            schemeContent.setCheckGuide(checkGuide.getCheckGuide());
                            schemeContent.setCheckProblem(checkGuide.getCheckProblem());
                        }
                        schemeContentMapper.insert(schemeContent);
                    }
                    Long contentId = schemeContent.getContentId();
                    //获取合理缺项
                    List<Map<String, Object>> checkMissingList = checkMissingListAll.stream().filter(map -> StringUtils.equals(contentId + "", map.get("CONTENT_ID") + "")).collect(Collectors.toList());
                    for (Map<String, Object> map : checkMissingList) {
                        map.put("is_selected", false);
                        if (schemeContent.getMissingItemContent() != null) {
                            if (schemeContent.getMissingItemContent().equals(String.valueOf(map.get("describe")))) {
                                map.put("is_selected", true);
                            }
                        }
                    }
                    if (!checkMissingList.isEmpty()) {
                        schemeContent.setCheckMissingList(checkMissingList);
                    }

                    //获取content的问题描述选项
                    List<Map<String, Object>> checkProblemList = checkProblemListAll.stream().filter(map -> StringUtils.equals(contentId + "", map.get("CONTENT_ID") + "")).collect(Collectors.toList());
                    if (StringUtils.equals("1", schemeContent.getProblemPreType())) {
                        for (Map<String, Object> map : checkProblemList) {
                            map.put("is_selected", false);
                            if (schemeContent.getProblemContent() != null) {
                                String[] problemArr = schemeContent.getProblemContent().split("##");
                                for (String problem : problemArr) {
                                    if (problem.equals(String.valueOf(map.get("DESCRIPTION")))) {
                                        map.put("is_selected", true);
                                    }
                                }
                            }
                        }
                    }
                    if (!checkMissingList.isEmpty()) {
                        schemeContent.setCheckProblemList(checkProblemList);
                    }
                    schemeContentList.add(schemeContent);
                }
                schemeStandard.setJgSchemeContentList(schemeContentList);
                schemeStandardList.add(schemeStandard);
            }
            schemePlanCheck.setJgSchemeStandardList(schemeStandardList);

        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("获取检查信息失败!");
        }
        System.out.println("schemePlanCheck:" + schemePlanCheck);
        return schemePlanCheck;

    }

    @Transactional(rollbackFor = Exception.class)
    public JgSchemePlanCheck uploadCheckFile(Long checkId, MultipartFile file) throws Exception {
        JgSchemePlanCheck dailyCheck = schemePlanCheckMapper.selectById(checkId);
        FileResultEntity fileEntity = FileUploadUtil.uploadImage(file, FileUploadEnum.schemePlan.getPath());
        try {
            dailyCheck.setComanyPic(fileEntity.getFilePath());
            dailyCheck.setComanyThumbnail(fileEntity.getFileThPath());
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("上传文件失败");
        }
        try {
            schemePlanCheckMapper.updateById(dailyCheck);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("保存告知单失败");
        }
        return dailyCheck;
    }


    /**
     * 保存告知单
     *
     * @param checkId
     * @param informFile
     * @param taskIds    关联的日常检查任务的任务id
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public String saveCheckInform(Long checkId, String informFile, String taskIds) {
        JgSchemePlanCheck dailyCheck = schemePlanCheckMapper.selectById(checkId);
        if (dailyCheck == null) {
            throw new RuntimeException("请先在检查内容中进行操作");
        }
        try {
            FileResultEntity informFileUrl = FileUploadUtil.uploadImageBase64Image(informFile, FileUploadEnum.schemePlan.getPath());
            dailyCheck.setInformUrl(informFileUrl.getFilePath());

            if (StringUtils.isNotEmpty(taskIds)) {
                String[] taskArray = taskIds.split(",");
                for (String taskId : taskArray) {
                    if (StringUtils.isEmpty(taskId)) {
                        continue;
                    }
                    JgDailyCheck dailyCheckH = dailyCheckMapper.selectById(Long.parseLong(taskId));
                    dailyCheckH.setInformUrl(informFileUrl.getFilePath());
                    dailyCheckMapper.updateById(dailyCheckH);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("上传文件失败");
        }

        try {
            schemePlanCheckMapper.updateById(dailyCheck);
            return dailyCheck.getInformUrl();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("保存告知单失败");
        }
    }

    /**
     * 保存/临时保存检查项结果内容
     *
     * @param taskIds 关联的日常检查任务的任务id
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public JgSchemePlanCheck saveCheckInfo(String temporary, JgSchemePlanCheck schemePlanCheck, String taskIds) {
        TcCompany company = tcCompanyMapper.selectById(schemePlanCheck.getCompanyId());
        schemePlanCheck.setInspType("3");
        schemePlanCheck.setInspBose("0");
        schemePlanCheck.setIsSpecialItem("0");
        //1.按主体ID查询最新的检查次数
        Integer checkNum = schemePlanCheckMapper.queryMaxCheckNumByCheckYearAndCompanyId((DateUtil.format(new Date(), "yyyy")), company.getId());
        schemePlanCheck.setCheckNum(checkNum == null ? 1 : checkNum + 1L);
        schemePlanCheck.setInspBoseName("食品生产监督检查要点表");
        if ("2".equals(temporary)) {
            schemePlanCheck.setCheckTime(DateUtil.format(new Date(), "yyyy-MM-dd"));
            schemePlanCheck.setCheckStat("1");
        } else {
            schemePlanCheck.setCheckStat("3");
        }
        //处理体系检查
        JgCheckResultTableSequence resultTableSequence = sequenceService.getResultTableSequence();
        Long resultRecordIndex = schemePlanCheck.getResultRecordIndex() == null ? resultTableSequence.getTableIndex() : schemePlanCheck.getResultRecordIndex();
        schemePlanCheck.setResultRecordIndex(resultRecordIndex);

        //保存检查内容列表信息
        saveItemListAndContentList(schemePlanCheck, schemePlanCheck.getManageStatus());
        if ("1".equals(schemePlanCheck.getManageStatus())) {
            //如果选择的是异常的话
            schemePlanCheck.setProcessResults("2");
            //保存异常信息
            saveEntAnomaly(company, schemePlanCheck, temporary);
        }
        schemePlanCheckMapper.updateById(schemePlanCheck);

        //保存被合并的任务信息
        if (StringUtils.isNotEmpty(taskIds)) {
            //合并任务选择了
            String[] taskArray = taskIds.split(",");
            for (String taskId : taskArray) {
                if (StringUtils.isEmpty(taskId)) {
                    continue;
                }
                JgDailyCheck dailyCheck = dailyCheckMapper.selectById(Long.parseLong(taskId));
                dailyCheck.setTemplateId(schemePlanCheck.getTemplateId());
                dailyCheck.setCheckTime(DateUtil.format(new Date(), "yyyy-MM-dd"));
                List<JgSchemePlanUser> schemePlanUserList = schemePlanUserMapper.selectByPlanId(schemePlanCheck.getPlantId());
                dailyCheck.setCheckPerson1Id(schemePlanUserList.size() > 0 ? schemePlanUserList.get(0).getUserId() : null);
                dailyCheck.setCheckPerson1Name(schemePlanUserList.size() > 0 ? schemePlanUserList.get(0).getUserName() : null);
                dailyCheck.setCheckPerson2Id(schemePlanUserList.size() > 1 ? schemePlanUserList.get(1).getUserId() : null);
                dailyCheck.setCheckPerson2Name(schemePlanUserList.size() > 1 ? schemePlanUserList.get(1).getUserName() : null);
                dailyCheck.setComanyPic(schemePlanCheck.getComanyPic());
                dailyCheck.setComanyThumbnail(schemePlanCheck.getComanyThumbnail());
                dailyCheck.setInformUrl(schemePlanCheck.getInformUrl());
                dailyCheck.setOtherProblem(schemePlanCheck.getOtherProblem());
                dailyCheck.setCheckItemTableUrl(schemePlanCheck.getCheckItemTableUrl());
                dailyCheck.setResultRecordUrl(schemePlanCheck.getResultRecordUrl());
                dailyCheck.setManageStatus(schemePlanCheck.getManageStatus());
                dailyCheck.setRectificationTimeLimit(schemePlanCheck.getRectificationTime());
                dailyCheck.setDelayCheck(schemePlanCheck.getDelayCheck() == null ? 0 : Integer.parseInt(schemePlanCheck.getDelayCheck()));
                dailyCheck.setVerificationRecords(schemePlanCheck.getVerificationRecords());
                dailyCheck.setAbnormalCause(schemePlanCheck.getAbnormalCause());
                dailyCheck.setAbnormalVerificationRecord(schemePlanCheck.getAbnormalVerificationRecord());
                dailyCheck.setDelayCheckDate(schemePlanCheck.getDelayCheckDate());
                dailyCheck.setCheckResult(schemePlanCheck.getCheckResult());
                dailyCheck.setTemplateName(schemePlanCheck.getTemplateName());
                if ("2".equals(temporary)) {
                    dailyCheck.setCheckTime(DateUtil.format(new Date(), "yyyy-MM-dd"));
                    dailyCheck.setCheckStat("1");
                } else {
                    dailyCheck.setCheckStat("3");
                }
                //保存检查内容列表信息
                saveDailyItemListAndContentList(schemePlanCheck, dailyCheck);
                if ("1".equals(schemePlanCheck.getManageStatus())) {
                    //如果选择的是异常的话
                    dailyCheck.setProcessResults("2");
                    //保存异常信息，合并的检查信息不生成异常信息
                    // schemePlanService.saveDailyEntAnomaly(jsEntAnomalyMapper, company, schemePlanCheck, dailyContentMapper, temporary,dailyCheck);
                }
                dailyCheckMapper.updateById(dailyCheck);
            }
        }


        //这里只做临时保存了
        return schemePlanCheck;
    }

    /**
     * 保存检查内容
     *
     * @param schemePlanCheck
     */
    @Transactional(rollbackFor = Exception.class)
    public void saveItemListAndContentList(JgSchemePlanCheck schemePlanCheck, String managerStatus) {
        List<JgSchemeStandard> schemeStandardList = schemePlanCheck.getJgSchemeStandardList();
        List<JgSchemeStandard> standardUpdateList = new ArrayList<>();
        List<JgSchemeContentFile> contentFileList = new ArrayList<>();
        List<JgSchemeContent> contentUpdateList = new ArrayList<>();
        for (JgSchemeStandard schemeStandard : schemeStandardList) {
            standardUpdateList.add(schemeStandard);
            //schemeStandardMapper.updateById(schemeStandard);
            List<JgSchemeContent> schemeContentList = schemeStandard.getJgSchemeContentList();
            for (JgSchemeContent schemeContent : schemeContentList) {
                if (StringUtils.isNotBlank(schemeContent.getProblemFile()) && schemeContent.getProblemFile().indexOf("data:image") >= 0) {
                    try {
                        FileResultEntity uploadEntity = FileUploadUtil.uploadImageBase64Image(schemeContent.getProblemFile(), FileUploadEnum.schemePlan.getPath());
                        String problemFile = schemeContent.getProblemFile();
                        schemeContent.setProblemFile(uploadEntity.getFilePath());

                        JgSchemeContentFile contentFile = new JgSchemeContentFile();
                        contentFile.setSchemeStandardId(schemeContent.getSchemeStandardId());
                        contentFile.setSchemeContentId(schemeContent.getId());
                        contentFile.setProblemFile(uploadEntity.getFilePath());
                        contentFile.setFilePicture(problemFile);
                        contentFile.setCreateTime(new Date());
                        contentFileList.add(contentFile);


                    } catch (Exception e) {
                        throw new RuntimeException("文件存储失败");
                    }
                }
                JgCheckContent checkContent = jgCheckContentMapper.selectById(schemeContent.getContentId());
                if (StringUtils.equals(managerStatus, "1")) {
                    schemeContent.setSelection("2");
                }
                if ("1".equals(schemeContent.getSelection())) {
                    schemeContent.setScore(checkContent.getYesScore());
                } else {
                    schemeContent.setScore(checkContent.getScore());
                }
                contentUpdateList.add(schemeContent);
                //schemeContentMapper.updateById(schemeContent);
            }
        }
        if (contentFileList.size() > 0) {
            contentFileMapper.batchInsert(contentFileList);
        }
        schemeStandardMapper.batchUpdate(standardUpdateList);
        schemeContentMapper.batchUpdate(contentUpdateList);

    }

    /**
     * 任务合并之后保存检查内容
     *
     * @param schemePlanCheck
     */
    @Transactional(rollbackFor = Exception.class)
    public void saveDailyItemListAndContentList(JgSchemePlanCheck schemePlanCheck, JgDailyCheck dailyCheck) {

        List<JgSchemeStandard> schemeStandardList = schemePlanCheck.getJgSchemeStandardList();
        //获取所有已经保存的检查大项
        List<JgDailyStandard> dailyStandardList = dailyStandardMapper.selectStandardByCheckId(dailyCheck.getId());

        // 准备批量操作集合
        List<JgDailyStandard> insertDailyStandards = new ArrayList<>();
        List<JgDailyStandard> updateDailyStandards = new ArrayList<>();
        List<JgDailyContent> insertDailyContents = new ArrayList<>();
        List<JgDailyContent> updateDailyContents = new ArrayList<>();
        Map<Long, JgDailyStandard> standardMapping = new HashMap<>();

        // 处理标准项
        for (JgSchemeStandard schemeStandard : schemeStandardList) {
            Optional<JgDailyStandard> dailyStandardOp = dailyStandardList.stream()
                    .filter(q -> Objects.equals(schemeStandard.getStandardId(), q.getStandardId()))
                    .findFirst();

            JgDailyStandard dailyStandard;
            if (!dailyStandardOp.isPresent()) {
                dailyStandard = new JgDailyStandard();
                dailyStandard.setTemplateId(schemeStandard.getTemplateId());
                dailyStandard.setStandardId(schemeStandard.getStandardId());
                dailyStandard.setSupCategory(schemeStandard.getSupCategory());
                dailyStandard.setSupProcess(schemeStandard.getSupProcess());
                dailyStandard.setSpxsId(schemeStandard.getSpxsId());
                dailyStandard.setCyfwId(schemeStandard.getCyfwId());
                dailyStandard.setSpscLbId(schemeStandard.getSpscLbId());
                dailyStandard.setSpscLbZlId(schemeStandard.getSpscLbZlId());
                dailyStandard.setTsspLbId(schemeStandard.getTsspLbId());
                dailyStandard.setTsspLbZlId(schemeStandard.getTsspLbZlId());
                dailyStandard.setName(schemeStandard.getName());
                dailyStandard.setSerialNum(schemeStandard.getSerialNum());
                dailyStandard.setDailyCheckId(dailyCheck.getId());
                dailyStandard.setCreateTime(new Date());
                dailyStandard.setCreatorId(UserHelper.getUserId());
                dailyStandard.setCreator(UserHelper.getUserInfo().getName());
                dailyStandard.setCreateDeptId(UserHelper.getUserInfo().getDeptId());
                dailyStandard.setCreateDeptName(UserHelper.getUserInfo().getDeptName());
                dailyStandard.setDeleteFlag(0L);
                insertDailyStandards.add(dailyStandard);
            } else {
                dailyStandard = dailyStandardOp.get();
                dailyStandard.setTemplateId(schemeStandard.getTemplateId());
                dailyStandard.setStandardId(schemeStandard.getStandardId());
                dailyStandard.setSupCategory(schemeStandard.getSupCategory());
                dailyStandard.setSupProcess(schemeStandard.getSupProcess());
                dailyStandard.setSpxsId(schemeStandard.getSpxsId());
                dailyStandard.setCyfwId(schemeStandard.getCyfwId());
                dailyStandard.setSpscLbId(schemeStandard.getSpscLbId());
                dailyStandard.setSpscLbZlId(schemeStandard.getSpscLbZlId());
                dailyStandard.setTsspLbId(schemeStandard.getTsspLbId());
                dailyStandard.setTsspLbZlId(schemeStandard.getTsspLbZlId());
                dailyStandard.setName(schemeStandard.getName());
                dailyStandard.setSerialNum(schemeStandard.getSerialNum());
                dailyStandard.setDailyCheckId(dailyCheck.getId());
                updateDailyStandards.add(dailyStandard);
            }
            standardMapping.put(schemeStandard.getStandardId(), dailyStandard);
        }

        // 批量处理标准项
        if (!insertDailyStandards.isEmpty()) {
            dailyStandardMapper.batchInsert(insertDailyStandards);
        }
        if (!updateDailyStandards.isEmpty()) {
            dailyStandardMapper.batchUpdate(updateDailyStandards);
        }

        // 处理内容项
        for (JgSchemeStandard schemeStandard : schemeStandardList) {
            JgDailyStandard dailyStandard = standardMapping.get(schemeStandard.getStandardId());
            List<JgDailyContent> existingContents = dailyContentMapper.selectByDailyStandard(dailyStandard.getId());

            for (JgSchemeContent schemeContent : schemeStandard.getJgSchemeContentList()) {
                Optional<JgDailyContent> contentOp = existingContents.stream()
                        .filter(q -> Objects.equals(schemeContent.getContentId(), q.getContentId()))
                        .findFirst();

                if (!contentOp.isPresent()) {
                    JgDailyContent dailyContent = new JgDailyContent();
                    dailyContent.setContentId(schemeContent.getContentId());
                    dailyContent.setDailyStandardId(dailyStandard.getId());
                    dailyContent.setCheckContent(schemeContent.getCheckContent());
                    dailyContent.setImportentItem(schemeContent.getImportentItem());
                    dailyContent.setMissingItem(schemeContent.getMissingItem());
                    dailyContent.setRemark(schemeContent.getRemark());
                    dailyContent.setScore(schemeContent.getScore());
                    dailyContent.setSerialNum(schemeContent.getSerialNum());
                    dailyContent.setSelection(schemeContent.getSelection());
                    dailyContent.setMissingItemContent(schemeContent.getMissingItemContent());
                    dailyContent.setProblemContent(schemeContent.getProblemContent());
                    dailyContent.setCreateTime(new Date());
                    dailyContent.setCreatorId(UserHelper.getUserId());
                    dailyContent.setCreator(UserHelper.getUserInfo().getName());
                    dailyContent.setCreateDeptId(UserHelper.getUserInfo().getDeptId());
                    dailyContent.setCreateDeptName(UserHelper.getUserInfo().getDeptName());
                    dailyContent.setProblemFile(schemeContent.getProblemFile());
                    dailyContent.setDeleteFlag(0L);
                    dailyContent.setStandardNum(schemeContent.getStandardNum());
                    dailyContent.setStandardName(schemeContent.getStandardName());
                    dailyContent.setProblemContentInput(schemeContent.getProblemContentInput());
                    dailyContent.setMissingItemContentInput(schemeContent.getMissingItemContentInput());
                    dailyContent.setCheckBasis(schemeContent.getCheckBasis());
                    dailyContent.setCheckMethod(schemeContent.getCheckMethod());
                    dailyContent.setCheckGuide(schemeContent.getCheckGuide());
                    dailyContent.setCheckProblem(schemeContent.getCheckProblem());
                    insertDailyContents.add(dailyContent);
                } else {
                    JgDailyContent dailyContent = contentOp.get();
                    dailyContent.setProblemContentInput(schemeContent.getProblemContentInput());
                    dailyContent.setMissingItemContentInput(schemeContent.getMissingItemContentInput());
                    dailyContent.setProblemFile(schemeContent.getProblemFile());
                    dailyContent.setMissingItemContent(schemeContent.getMissingItemContent());
                    dailyContent.setProblemContent(schemeContent.getProblemContent());
                    dailyContent.setSelection(schemeContent.getSelection());
                    dailyContent.setRemark(schemeContent.getRemark());
                    updateDailyContents.add(dailyContent);
                }
            }
        }
        // 批量处理内容项
        if (!insertDailyContents.isEmpty()) {
            dailyContentMapper.batchInsert(insertDailyContents);
        }
        if (!updateDailyContents.isEmpty()) {
            dailyContentMapper.batchUpdate(updateDailyContents);
        }
    }/*
     *//**
     * 任务合并之后保存检查内容
     * @param dailyStandardMapper
     * @param schemePlanCheck
     *//*
    public void saveDailyItemListAndContentList(JgDailyStandardMapper dailyStandardMapper,
                                                 JgDailyContentMapper dailyContentMapper, JgSchemePlanCheck schemePlanCheck, JgDailyCheck dailyCheck) {

        List<JgSchemeStandard> schemeStandardList = schemePlanCheck.getJgSchemeStandardList();
        //获取所有已经保存的检查大项
        List<JgDailyStandard> dailyStandardList = dailyStandardMapper.selectStandardByCheckId(dailyCheck.getId());
        for (JgSchemeStandard schemeStandard : schemeStandardList) {
            Optional<JgDailyStandard> dailyStandardOp = dailyStandardList.stream().filter(qdailyStandard -> Objects.equals(schemeStandard.getStandardId(), qdailyStandard.getStandardId())).findFirst();// dailyStandardMapper.selectStandard(schemeStandard.getStandardId(),dailyCheck.getId());
            JgDailyStandard dailyStandard;
            if(!dailyStandardOp.isPresent()){
                dailyStandard = new JgDailyStandard();
                dailyStandard.setTemplateId(schemeStandard.getTemplateId());
                dailyStandard.setStandardId(schemeStandard.getStandardId());
                dailyStandard.setSupCategory(schemeStandard.getSupCategory());
                dailyStandard.setSupProcess(schemeStandard.getSupProcess());
                dailyStandard.setSpxsId(schemeStandard.getSpxsId());
                dailyStandard.setCyfwId(schemeStandard.getCyfwId());
                dailyStandard.setSpscLbId(schemeStandard.getSpscLbId());
                dailyStandard.setSpscLbZlId(schemeStandard.getSpscLbZlId());
                dailyStandard.setTsspLbId(schemeStandard.getTsspLbId());
                dailyStandard.setTsspLbZlId(schemeStandard.getTsspLbZlId());
                dailyStandard.setName(schemeStandard.getName());
                dailyStandard.setSerialNum(schemeStandard.getSerialNum());
                dailyStandard.setDailyCheckId(dailyCheck.getId());
                dailyStandard.setCreateTime(new Date());
                dailyStandard.setCreatorId(UserHelper.getUserId());
                dailyStandard.setCreator(UserHelper.getUserInfo().getName());
                dailyStandard.setCreateDeptId(UserHelper.getUserInfo().getDeptId());
                dailyStandard.setCreateDeptName(UserHelper.getUserInfo().getDeptName());
                dailyStandard.setDeleteFlag(0L);
                dailyStandardMapper.insert(dailyStandard);
            } else {
                dailyStandard = dailyStandardOp.get();
                dailyStandardMapper.updateById(dailyStandard);
            }

            List<JgSchemeContent> schemeContentList = schemeStandard.getJgSchemeContentList();
            List<JgDailyContent> dailyContentList = dailyContentMapper.selectByDailyStandard(dailyStandard.getId());
            for (JgSchemeContent schemeContent : schemeContentList) {
                Optional<JgDailyContent> dailyContentOp = dailyContentList.stream().filter(qDailyContent -> Objects.equals(schemeContent.getContentId(), qDailyContent.getContentId())).findFirst();
                JgDailyContent dailyContent;
                if(!dailyContentOp.isPresent()){
                    dailyContent = new JgDailyContent();
                    dailyContent.setContentId(schemeContent.getContentId());
                    dailyContent.setDailyStandardId(dailyStandard.getId());
                    dailyContent.setCheckContent(schemeContent.getCheckContent());
                    dailyContent.setImportentItem(schemeContent.getImportentItem());
                    dailyContent.setMissingItem(schemeContent.getMissingItem());
                    dailyContent.setRemark(schemeContent.getRemark());
                    dailyContent.setScore(schemeContent.getScore());
                    dailyContent.setSerialNum(schemeContent.getSerialNum());
                    dailyContent.setSelection(schemeContent.getSelection());
                    dailyContent.setMissingItemContent(schemeContent.getMissingItemContent());
                    dailyContent.setProblemContent(schemeContent.getProblemContent());
                    dailyContent.setCreateTime(new Date());
                    dailyContent.setCreatorId(UserHelper.getUserId());
                    dailyContent.setCreator(UserHelper.getUserInfo().getName());
                    dailyContent.setCreateDeptId(UserHelper.getUserInfo().getDeptId());
                    dailyContent.setCreateDeptName(UserHelper.getUserInfo().getDeptName());
                    dailyContent.setProblemFile(schemeContent.getProblemFile());
                    dailyContent.setDeleteFlag(0L);
                    dailyContent.setStandardNum(schemeContent.getStandardNum());
                    dailyContent.setStandardName(schemeContent.getStandardName());
                    dailyContent.setProblemContentInput(schemeContent.getProblemContentInput());
                    dailyContent.setMissingItemContentInput(schemeContent.getMissingItemContentInput());
                    dailyContent.setCheckBasis(schemeContent.getCheckBasis());
                    dailyContent.setCheckMethod(schemeContent.getCheckMethod());
                    dailyContent.setCheckGuide(schemeContent.getCheckGuide());
                    dailyContent.setCheckProblem(schemeContent.getCheckProblem());
                    dailyContentMapper.insert(dailyContent);
                } else {
                    dailyContent = dailyContentOp.get();
                    dailyContent.setProblemContentInput(schemeContent.getProblemContentInput());
                    dailyContent.setMissingItemContentInput(schemeContent.getMissingItemContentInput());
                    dailyContent.setProblemFile(schemeContent.getProblemFile());
                    dailyContent.setMissingItemContent(schemeContent.getMissingItemContent());
                    dailyContent.setProblemContent(schemeContent.getProblemContent());
                    dailyContent.setSelection(schemeContent.getSelection());
                    dailyContent.setRemark(schemeContent.getRemark());
                    dailyContentMapper.updateById(dailyContent);
                }
            }
        }
    }*/

    /**
     * 保存检查异常的信息
     *
     * @param company         企业信息
     * @param schemePlanCheck 检查信息
     * @param temporary
     */
    @Transactional(rollbackFor = Exception.class)
    public void saveEntAnomaly(TcCompany company,
                               JgSchemePlanCheck schemePlanCheck, String temporary) {
        JsEntAnomaly jsEntAnomaly = jsEntAnomalyMapper.selectByCheckId(schemePlanCheck.getId(), "4");
        if (jsEntAnomaly == null) {
            jsEntAnomaly = new JsEntAnomaly();
        }
        jsEntAnomaly.setCheckType("4");
        jsEntAnomaly.setCompanyId(company.getId());
        jsEntAnomaly.setCompanyName(company.getCompanyName());
        jsEntAnomaly.setCreditCode(company.getCreditCode());
        jsEntAnomaly.setLicense(company.getLicense());
        jsEntAnomaly.setDailyCheckId(schemePlanCheck.getId());
        jsEntAnomaly.setAbnormalCause(schemePlanCheck.getAbnormalCause());
        jsEntAnomaly.setAuditTrails(schemePlanCheck.getVerificationRecords());
        jsEntAnomaly.setRectifyTime(schemePlanCheck.getRectificationTime());
        jsEntAnomaly.setCheckResults(schemePlanCheck.getCheckResult());
        jsEntAnomaly.setProcessResults(schemePlanCheck.getProcessResults());
        if (!"2".equals(temporary)) {
            //临时存储的
            jsEntAnomaly.setDeleteFlag(2L);
        } else {
            //正式存储的
            jsEntAnomaly.setDeleteFlag(0L);
        }
        int checkNum = 0;
        //修改所有的检查内容为选择的否
        List<JgSchemeStandard> schemeStandardList = schemePlanCheck.getJgSchemeStandardList();
        for (JgSchemeStandard schemeStandard : schemeStandardList) {
            List<JgSchemeContent> schemeContentList = schemeStandard.getJgSchemeContentList();
            for (JgSchemeContent schemeContent : schemeContentList) {

                if (schemeContent.getSelection().equals("2")) {
                    checkNum = checkNum + 1;
                }
                //schemeContent.setSelection("2");
                //schemeContentMapper.updateById(schemeContent);
            }
        }
        jsEntAnomaly.setCheckNumber(checkNum);
        if (jsEntAnomaly.getId() == null) {
            jsEntAnomaly.setCreateTime(new Date());
            jsEntAnomaly.setCreatorId(UserHelper.getUserId());
            jsEntAnomaly.setCreator(UserHelper.getUserInfo().getName());
            jsEntAnomalyMapper.insert(jsEntAnomaly);
        } else {
            jsEntAnomalyMapper.updateById(jsEntAnomaly);
        }

    }


    /**
     * 保存合并的日常检查的异常的信息
     *
     * @param thjsEntAnomalyMapper 异常mapper
     * @param company              企业信息
     * @param schemePlanCheck      检查信息
     * @param temporary
     */
    @Transactional(rollbackFor = Exception.class)
    public void saveDailyEntAnomaly(JsEntAnomalyMapper thjsEntAnomalyMapper, TcCompany company,
                                    JgSchemePlanCheck schemePlanCheck, JgDailyContentMapper dailyContentMapper, String temporary, JgDailyCheck dailyCheck) {
        JsEntAnomaly jsEntAnomaly = thjsEntAnomalyMapper.selectByCheckId(schemePlanCheck.getId(), "1");
        if (jsEntAnomaly == null) {
            jsEntAnomaly = new JsEntAnomaly();
        }
        jsEntAnomaly.setCheckType("1");
        jsEntAnomaly.setCompanyId(company.getId());
        jsEntAnomaly.setCompanyName(company.getCompanyName());
        jsEntAnomaly.setCreditCode(company.getCreditCode());
        jsEntAnomaly.setLicense(company.getLicense());
        jsEntAnomaly.setDailyCheckId(dailyCheck.getId());
        jsEntAnomaly.setAbnormalCause(schemePlanCheck.getAbnormalCause());
        jsEntAnomaly.setAuditTrails(schemePlanCheck.getVerificationRecords());
        jsEntAnomaly.setRectifyTime(schemePlanCheck.getRectificationTime());
        jsEntAnomaly.setCheckResults(schemePlanCheck.getCheckResult());
        jsEntAnomaly.setProcessResults(schemePlanCheck.getProcessResults());
        if (!"2".equals(temporary)) {
            //临时存储的
            jsEntAnomaly.setDeleteFlag(2L);
        } else {
            //正式存储的
            jsEntAnomaly.setDeleteFlag(0L);
        }
        if (jsEntAnomaly.getId() == null) {
            jsEntAnomaly.setCreateTime(new Date());
            jsEntAnomaly.setCreatorId(UserHelper.getUserId());
            jsEntAnomaly.setCreator(UserHelper.getUserInfo().getName());
            thjsEntAnomalyMapper.insert(jsEntAnomaly);
        } else {
            thjsEntAnomalyMapper.updateById(jsEntAnomaly);
        }
        if (!"2".equals(temporary)) {
            //临时存储的先不存储下面的检查内容
            return;
        }

        String supProcess = company.getSupProcess();
        int checkNum = 0;
        //修改所有的检查内容为选择的否
        List<JgSchemeStandard> schemeStandardList = schemePlanCheck.getJgSchemeStandardList();
        for (JgSchemeStandard schemeStandard : schemeStandardList) {
            List<JgSchemeContent> schemeContentList = schemeStandard.getJgSchemeContentList();
            for (JgSchemeContent schemeContent : schemeContentList) {
                checkNum = checkNum + 1;
                schemeContent.setSelection("2");
                schemeContentMapper.updateById(schemeContent);
            }
        }
        jsEntAnomaly.setCheckNumber(checkNum);
        thjsEntAnomalyMapper.updateById(jsEntAnomaly);
    }


    /**
     * 最终保存
     *
     * @param checkId
     * @param taskIds 关联的日常检查任务的任务id
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public JgSchemePlanCheck finaSaveInfo(Long checkId, String taskIds) {
        JgSchemePlanCheck dailyCheck = schemePlanCheckMapper.selectById(checkId);
        dailyCheck.setCheckStat("1");
        dailyCheck.setCheckTime(DateUtil.format(new Date(), "yyyy-MM-dd"));
        schemePlanCheckMapper.updateById(dailyCheck);
        TcCompany company = tcCompanyMapper.selectById(dailyCheck.getCompanyId());
        //如果选择的不是通过的话生成相应的后续步骤
        if ("2".equals(dailyCheck.getProcessResults())) {
            //责令整改
            saveRectification(dailyCheck.getRectificationTime(), company, dailyCheck);
        } else if ("3".equals(dailyCheck.getProcessResults())) {
            //选择调查处理同时也要生成一个整改信息
            saveRectification(dailyCheck.getRectificationTime(), company, dailyCheck);
            //调查处理,查看调查处理开关是否打开
            JgInvestigationSet investigationSet = investigationSetMapper.selectByCheckTypeAndProcess("5", company.getSupProcess());
            //调查处理开关打开的情况下才生成下面的内容
            if ("1".equals(investigationSet == null ? "2" : investigationSet.getCheckStatus())) {
                saveInvestigation(company, dailyCheck);
            }
        }


        JsEntAnomaly jsEntAnomaly = jsEntAnomalyMapper.selectByCheckId(dailyCheck.getId(), "4");
        if (jsEntAnomaly != null) {
            jsEntAnomaly.setDeleteFlag(0L);
            jsEntAnomalyMapper.updateById(jsEntAnomaly);
        }


        //保存最新数据到评级的分数表，每年评级的时候要用
        List<JgSchemeContent> dailyContentList = schemeContentMapper.selectByCheckId(checkId);
        for (JgSchemeContent dailyContentMap : dailyContentList) {
            JgScDynamicScoring jgScDynamicScoring = scDynamicScoringMapper.selectByContentIdAndCompanyId(dailyContentMap.getContentId(), dailyCheck.getCompanyId());
            if (jgScDynamicScoring == null) {
                jgScDynamicScoring = new JgScDynamicScoring();
                jgScDynamicScoring.setContentId(dailyContentMap.getContentId());
                jgScDynamicScoring.setCheckContent(dailyContentMap.getCheckContent());
                jgScDynamicScoring.setCompanyId(dailyCheck.getCompanyId());
                jgScDynamicScoring.setScore(dailyContentMap.getScore());
                jgScDynamicScoring.setSelection(dailyContentMap.getSelection());
                jgScDynamicScoring.setCreatorId(UserHelper.getUserId());
                jgScDynamicScoring.setCreatorName(UserHelper.getUserInfo().getName());
                jgScDynamicScoring.setCreateTime(new Date());
                jgScDynamicScoring.setDeleteFlag("0");
                scDynamicScoringMapper.insert(jgScDynamicScoring);
            } else {
                jgScDynamicScoring.setUpdateTime(new Date());
                jgScDynamicScoring.setUpdateName(UserHelper.getUserInfo().getName());
                jgScDynamicScoring.setUpdateId(UserHelper.getUserId());
                scDynamicScoringMapper.updateById(jgScDynamicScoring);
            }
        }

        //最终保存被合并的任务信息
        if (StringUtils.isNotEmpty(taskIds)) {
            String[] taskArray = taskIds.split(",");
            for (String taskId : taskArray) {
                if (StringUtils.isEmpty(taskId)) {
                    continue;
                }
                JgDailyCheck dailyCheckH = dailyCheckMapper.selectById(Long.parseLong(taskId));
                dailyCheckH.setCheckStat("1");
                dailyCheckH.setCheckTime(DateUtil.format(new Date(), "yyyy-MM-dd"));
                dailyCheckMapper.updateById(dailyCheckH);
            }
        }
        return dailyCheck;
    }

    /**
     * 保存整改信息
     *
     * @param rectificationTimeLimit 整改期限
     * @param company                企业信息
     * @param dailyCheck             日常检查信息
     */
    @Transactional(propagation = Propagation.REQUIRED)
    public void saveRectification(String rectificationTimeLimit,
                                  TcCompany company, JgSchemePlanCheck dailyCheck) {
        //如果已经存在整改单信息说明之前保存完成了 属于流程操作错误问题不进行保存
        List<JgRectification> rectifications = rectificationMapper.selectByCheckId(dailyCheck.getId(), "4");
        JgRectification rectification;
        if (rectifications.size() > 0) {
            rectification = rectifications.get(0);
        } else {
            rectification = new JgRectification();
        }
        rectification.setCompanyId(company.getId());
        rectification.setCheckId(dailyCheck.getId());
        rectification.setCheckType("4");
        rectification.setCheckStatus("1");
        rectification.setRectificationTimeLimit(rectificationTimeLimit);
        rectification.setCreateTime(new Date());
        rectification.setCreatorId(UserHelper.getUserId());
        rectification.setCreatorName(UserHelper.getUserInfo().getName());
        rectification.setDeleteFlag(0L);
        if (rectification.getId() == null) {
            rectificationMapper.insert(rectification);
        } else {
            rectificationMapper.updateById(rectification);

        }

        //保存整改内容的初始信息
        if (!StringUtils.equals(dailyCheck.getManageStatus(), "1")) {
            //选择的不是经营异常才存储这个问题项
            List<JgSchemeContent> dailyContent = schemeContentMapper.selectNoPassByCheckId(dailyCheck.getId());
            List<JgRectificationContent> rectificationContents = new ArrayList<>();
            for (JgSchemeContent jgDailyContent : dailyContent) {
                JgRectificationContent rectificationContent = new JgRectificationContent();
                rectificationContent.setRectificationId(rectification.getId());
                rectificationContent.setCheckType("1");
                rectificationContent.setCheckContentId(jgDailyContent.getId());
                rectificationContent.setCreateTime(new Date());
                rectificationContent.setCreatorId(UserHelper.getUserId());
                rectificationContent.setCreatorName(UserHelper.getUserInfo().getName());
                rectificationContent.setDeleteFlag(0L);
                rectificationContent.setSerialNum(jgDailyContent.getStandardNum());
                rectificationContent.setStandardName(jgDailyContent.getStandardName());
                rectificationContent.setContentNum(jgDailyContent.getSerialNum());
                rectificationContent.setCheckContent(jgDailyContent.getCheckContent());
                rectificationContent.setSelection(jgDailyContent.getSelection());
                rectificationContent.setProblemContent(jgDailyContent.getProblemContent());
                rectificationContent.setProblemFile(jgDailyContent.getProblemFile());
                rectificationContent.setProblemContentInput(jgDailyContent.getProblemContentInput());
                rectificationContent.setMissingItemContentInput(jgDailyContent.getMissingItemContentInput());
                rectificationContent.setMissingItemContent(jgDailyContent.getMissingItemContent());
//            rectificationContentMapper.insert(rectificationContent);
                rectificationContents.add(rectificationContent);
            }
            if (!rectificationContents.isEmpty()) {
                rectificationContentMapper.batchInsert(rectificationContents);
            }
        }
    }


    /**
     * 保存调查处理
     *
     * @param company    企业信息
     * @param dailyCheck 日常检查信息
     */
    @Transactional(propagation = Propagation.REQUIRED)
    public void saveInvestigation(TcCompany company, JgSchemePlanCheck dailyCheck) {
        //如果已经存在整改单信息说明之前保存完成了 属于流程操作错误问题不进行保存
        List<JgInvestigation> investigations = investigationMapper.selectByCheckId(dailyCheck.getId(), "4");
        JgInvestigation investigation;
        if (investigations.size() > 0) {
            investigation = investigations.get(0);
        } else {
            investigation = new JgInvestigation();
        }
        investigation.setCompanyId(company.getId());
        investigation.setCheckId(dailyCheck.getId());
        investigation.setCheckType("4");
        investigation.setCheckStatus("1");
        investigation.setCreateTime(new Date());
        investigation.setCreatorId(UserHelper.getUserId());
        investigation.setCreatorName(UserHelper.getUserInfo().getName());
        investigation.setDeleteFlag(0L);
        investigation.setCheckPersonnel(UserHelper.getUserId());//处理人员，谁检查的就是谁
        investigation.setCheckPersonnelName(UserHelper.getUserInfo().getName());
        if (investigation.getId() == null) {
            investigationMapper.insert(investigation);
        } else {
            investigationMapper.updateById(investigation);
        }
        //保存整改内容的初始信息
        List<JgSchemeContent> dailyContent = schemeContentMapper.selectNoPassByCheckId(dailyCheck.getId());
        List<JgInvestigationContent> investigationContents = new ArrayList<>();
        for (JgSchemeContent jgDailyContent : dailyContent) {
            JgInvestigationContent investigationContent = new JgInvestigationContent();
            investigationContent.setInvestigationId(investigation.getId());
            investigationContent.setCheckType("4");
            investigationContent.setCheckContentId(jgDailyContent.getId());
            investigationContent.setCreateTime(new Date());
            investigationContent.setCreatorId(UserHelper.getUserId());
            investigationContent.setCreatorName(UserHelper.getUserInfo().getName());
            investigationContent.setDeleteFlag(0L);
            investigationContent.setSerialNum(jgDailyContent.getStandardNum());
            investigationContent.setStandardName(jgDailyContent.getStandardName());
            investigationContent.setContentNum(jgDailyContent.getSerialNum());
            investigationContent.setCheckContent(jgDailyContent.getCheckContent());
            investigationContent.setSelection(jgDailyContent.getSelection());
            investigationContent.setProblemContent(jgDailyContent.getProblemContent());
            investigationContent.setProblemFile(jgDailyContent.getProblemFile());
            investigationContent.setProblemContentInput(jgDailyContent.getProblemContentInput());
            investigationContent.setMissingItemContent(jgDailyContent.getMissingItemContent());
            investigationContent.setMissingItemContentInput(jgDailyContent.getMissingItemContentInput());
//            investigationContentMapper.insert(investigationContent);
            investigationContents.add(investigationContent);
        }
        investigationContentMapper.batchInsert(investigationContents);
    }

    /**
     * 上传结果记录的文件
     *
     * @param checkId 日常检查结果表id
     * @param imgFile 二进制文件流
     * @param type    1-要点表；2-记录表
     * @return
     */

    @Transactional(rollbackFor = Exception.class)
    public String uploadResultRecord(Long checkId, MultipartFile imgFile, String type) throws Exception {
        JgSchemePlanCheck dailyCheck = schemePlanCheckMapper.selectById(checkId);
        if (imgFile != null && StringUtils.isNoneBlank(imgFile.getOriginalFilename())) {
            FileResultEntity fileResultEntity = FileUploadUtil.uploadImage(imgFile, FileUploadEnum.schemePlan.getPath());
            if ("1".equals(type)) {
                dailyCheck.setCheckItemTableUrl(fileResultEntity.getFilePath());
            } else if ("2".equals(type)) {
                dailyCheck.setResultRecordUrl(fileResultEntity.getFilePath());
            }
            schemePlanCheckMapper.updateById(dailyCheck);
            return fileResultEntity.getFilePath();
        }
        return "";
    }


    /**
     * 查询检查信息
     *
     * @param checkId 检查id
     * @return
     */
    public JgSchemePlanCheck getCheckInfo(Long checkId) {
        JgSchemePlanCheck dailyCheck = schemePlanCheckMapper.selectById(checkId);
        QueryWrapper<JgSchemeStandard> dailyStandardQueryWrapper = new QueryWrapper<>();
        dailyStandardQueryWrapper.eq("delete_flag", "0");
        dailyStandardQueryWrapper.eq("SCHEME_PLAN_CHECK_ID", checkId);
        List<JgSchemeStandard> standardList = schemeStandardMapper.selectList(dailyStandardQueryWrapper);
        for (JgSchemeStandard jgDailyStandard : standardList) {
            QueryWrapper<JgSchemeContent> dailyContentQueryWrapper = new QueryWrapper<>();
            dailyContentQueryWrapper.eq("delete_flag", "0");
            dailyContentQueryWrapper.eq("SCHEME_STANDARD_ID", jgDailyStandard.getId());
            List<JgSchemeContent> contentList = schemeContentMapper.selectList(dailyContentQueryWrapper);
            jgDailyStandard.setJgSchemeContentList(contentList);
        }
        List<JgSchemePlanUser> schemePlanUser = schemePlanUserMapper.selectByPlanId(dailyCheck.getPlantId());
        dailyCheck.setSchemePlanUserList(schemePlanUser);
        dailyCheck.setJgSchemeStandardList(standardList);
        return dailyCheck;
    }

    /**
     * 查询结果表需要的数据
     *
     * @param checkId 日常检查表JG_DAILY_CHECK  id
     * @return
     */
    public Map<String, Object> getResultTable(Long checkId) {
        Map<String, Object> checkInfo = schemePlanCheckMapper.selectMapById(checkId);
        List<Map<String, Object>> contentList = schemeContentMapper.selectMapByCheckId(checkId);
        Integer contentNum = contentList.size();
        Integer importNum = 0; //重点项
        Integer importProblemNum = 0; //发现问题
        Integer commonlyNum = 0; //一般项
        Integer commonlyProblemNum = 0; //发现问题
        List<String> importNo = new ArrayList<>();//重点项序号
        List<String> importProblemNo = new ArrayList<>();//重点项序号
        List<String> commonlyNo = new ArrayList<>();//一般项序号
        List<String> commonlyProblemNo = new ArrayList<>();//一般项序号
        Pattern pattern = Pattern.compile("^\\d+(\\.\\d+)?");
        for (Map<String, Object> content : contentList) {
            //IMPORTENT_ITEM is '重要项：1一般项，2重要项
            //SELECTION is '选择项：1是、2否、3合理缺项
            if (StringUtils.equals(content.get("IMPORTENT_ITEM") + "", "1")) {
                commonlyNum = commonlyNum + 1;
                Matcher matcher = pattern.matcher(content.get("CHECK_CONTENT").toString());
                Matcher dxmatcher = pattern.matcher(content.get("DX_SERIAL_NUM").toString());
                String dxNumber = (dxmatcher.find() && StringUtils.isNotBlank(dxmatcher.group())) ? dxmatcher.group() : content.get("DX_SERIAL_NUM") + "";
                if (matcher.find() && StringUtils.isNotBlank(matcher.group())) {
                    String number = matcher.group();
                    commonlyProblemNo.add(dxNumber + "." + number);
                    if (StringUtils.equals(content.get("SELECTION") + "", "2")) {
                        commonlyProblemNo.add(dxNumber + "." + number);
                    }
                } else {
                    //如果内容文字不匹配则查询序号字段
                    commonlyNo.add(content.get("DX_SERIAL_NUM") + "." + content.get("SERIAL_NUM"));
                    if (StringUtils.equals(content.get("SELECTION") + "", "2")) {
                        commonlyProblemNo.add(content.get("DX_SERIAL_NUM") + "." + content.get("SERIAL_NUM"));
                    }
                }
                if (StringUtils.equals(content.get("SELECTION") + "", "2")) {
                    commonlyProblemNum = commonlyProblemNum + 1;
                }

            } else if (StringUtils.equals(content.get("IMPORTENT_ITEM") + "", "2")) {
                importNum = importNum + 1;
                Matcher matcher = pattern.matcher(content.get("CHECK_CONTENT").toString());
                if (matcher.find() && StringUtils.isNotBlank(matcher.group())) {
                    Matcher dxmatcher = pattern.matcher(content.get("DX_SERIAL_NUM").toString());
                    String dxNumber = (dxmatcher.find() && StringUtils.isNotBlank(dxmatcher.group())) ? dxmatcher.group() : content.get("DX_SERIAL_NUM") + "";
                    String number = matcher.group();
                    importNo.add(dxNumber + "." + number);
                    if (StringUtils.equals(content.get("SELECTION") + "", "2")) {
                        importProblemNo.add(dxNumber + "." + number);
                    }
                } else {
                    //如果内容文字不匹配则查询序号字段
                    importNo.add(content.get("DX_SERIAL_NUM") + "." + content.get("SERIAL_NUM"));
                    if (StringUtils.equals(content.get("SELECTION") + "", "2")) {
                        importProblemNo.add(content.get("DX_SERIAL_NUM") + "." + content.get("SERIAL_NUM"));
                    }
                }
                if (StringUtils.equals(content.get("SELECTION") + "", "2")) {
                    importProblemNum = importProblemNum + 1;
                }
            }
        }

        if (checkInfo.get("CHECK_PERSON1_ID") != null) {
            TsUser user1 = userMapper.selectById(Integer.valueOf(checkInfo.get("CHECK_PERSON1_ID").toString()));
            checkInfo.put("enforcementNo1", user1.getEnforcementNo());
            checkInfo.put("enforcementName1", user1.getName());
        }
        if (checkInfo.get("CHECK_PERSON2_ID") != null) {
            TsUser user2 = userMapper.selectById(Integer.valueOf(checkInfo.get("CHECK_PERSON2_ID").toString()));
            checkInfo.put("enforcementNo2", user2.getEnforcementNo());
            checkInfo.put("enforcementName2", user2.getName());
        }
     /*   QueryWrapper<JgFlightPlanCheck> flightPlanCheckQueryWrapper = new QueryWrapper<>();
        flightPlanCheckQueryWrapper.eq("delete_flag","0");
        flightPlanCheckQueryWrapper.eq("CHECK_STAT", "1");
        flightPlanCheckQueryWrapper.eq("company_id",checkInfo.get("COMPANY_ID"));
        flightPlanCheckQueryWrapper.eq("date_format(CHECK_TIME,'%Y')",DateUtil.year(new Date()));
        Long flightPlanCheckCount = flightPlanCheckMapper.selectCount(flightPlanCheckQueryWrapper);

        QueryWrapper<JgSchemePlanCheck> schemePlanCheckQueryWrapper = new QueryWrapper<>();
        schemePlanCheckQueryWrapper.eq("delete_flag","0");
        flightPlanCheckQueryWrapper.eq("CHECK_STAT", "1");
        schemePlanCheckQueryWrapper.eq("company_id",checkInfo.get("COMPANY_ID"));
        schemePlanCheckQueryWrapper.eq("date_format(CHECK_TIME,'%Y')",DateUtil.year(new Date()));
        Long schemePlanCheckCount = schemePlanCheckMapper.selectCount(schemePlanCheckQueryWrapper);

        QueryWrapper<JgDailyCheck> jgDailyCheckQueryWrapper = new QueryWrapper<>();
        jgDailyCheckQueryWrapper.eq("delete_flag","0");
        jgDailyCheckQueryWrapper.eq("CHECK_STAT", "1");
        jgDailyCheckQueryWrapper.eq("company_id",checkInfo.get("COMPANY_ID"));
        jgDailyCheckQueryWrapper.eq("CHECK_YEAR",DateUtil.year(new Date()));
        Long dailyCheckCount = dailyCheckMapper.selectCount(jgDailyCheckQueryWrapper);*/

//        checkInfo.put("CHECK_NUM", flightPlanCheckCount + schemePlanCheckCount + dailyCheckCount + 1 );
        checkInfo.put("contentNum", contentNum);
        checkInfo.put("importNum", importNum);
        checkInfo.put("importProblemNum", importProblemNum);
        checkInfo.put("commonlyNum", commonlyNum);
        checkInfo.put("commonlyProblemNum", commonlyProblemNum);
        checkInfo.put("importNo", String.join(" ; ", importNo));
        checkInfo.put("importProblemNo", String.join(" ; ", importProblemNo));
        checkInfo.put("commonlyNo", String.join(" ; ", commonlyNo));
        checkInfo.put("commonlyProblemNo", String.join(" ; ", commonlyProblemNo));

        //生成单子编号
//        TcCompany company = tcCompanyMapper.selectEntityById(Long.parseLong(checkInfo.get("COMPANY_ID").toString()));
        JgSchemePlanCheck schemePlanCheck = schemePlanCheckMapper.selectById(checkId);
        //检查单今年的流水号
        if (schemePlanCheck.getResultRecordIndex() == null) {
            //当前单子未生成过.如果第二次保存结果记录表，则直接使用第一次的序号来生成
            JgCheckResultTableSequence resultTableSequence = sequenceService.getResultTableSequence();
            schemePlanCheck.setResultRecordIndex(resultTableSequence.getTableIndex());//加一并获取
            schemePlanCheckMapper.updateById(schemePlanCheck);
        }
        //序号按照6位数在签名补0
        Long index = schemePlanCheck.getResultRecordIndex();
        String resultCode = SequenceService.generatorProResultTableCode(index);
        checkInfo.put("resultCode", resultCode);
        return checkInfo;
    }

    /**
     * 获取检查结果记录
     *
     * @param checkId
     * @return
     */
    public Map<String, Object> getCheckResultInfo(Long checkId) {
        Map<String, Object> result = new HashMap<>();
        //检查结果
        Map<String, Object> checkInfo = new HashMap<>();
        //获取和各项，不合格项，合理缺项比例
        JgSchemePlanCheck dailyCheck = schemePlanCheckMapper.selectById(checkId);
        List<JgSchemePlanUser> schemePlanUser = schemePlanUserMapper.selectByPlanId(dailyCheck.getPlantId());

        List<Map<String, Object>> contentList = schemeContentMapper.selectMapByCheckId(checkId);
        int hege = 0;
        int buhege = 0;
        int heliquexiang = 0;

        if ("1".equals(dailyCheck.getManageStatus())) {
            JsEntAnomaly entAnomaly = jsEntAnomalyMapper.selectByCheckId(dailyCheck.getId(), "4");
            checkInfo.put("CHECK_RESULTS", entAnomaly.getCheckResults());
            checkInfo.put("ECHARTS_QUALIFIED", hege);
            checkInfo.put("ECHARTS_NOQUALIFIED", entAnomaly.getCheckNumber());
            checkInfo.put("ECHARTS_MISSING_ITEM", heliquexiang);
        } else {
            checkInfo.put("CHECK_RESULTS", dailyCheck.getCheckResult());
            // is '选择项：1是、2否、3合理缺项'
            for (Map<String, Object> content : contentList) {
                String selection = content.get("SELECTION") + "";
                switch (selection) {
                    case "1":
                        hege++;
                        break;
                    case "2":
                        buhege++;
                        break;
                    case "3":
                        heliquexiang++;
                        break;
                }
            }
            checkInfo.put("ECHARTS_QUALIFIED", hege);
            checkInfo.put("ECHARTS_NOQUALIFIED", buhege);
            checkInfo.put("ECHARTS_MISSING_ITEM", heliquexiang);
        }

        //处理结果：1通过检查，2责令整改，3调查处理
        checkInfo.put("PROCESS_RESULTS", dailyCheck.getProcessResults());
        checkInfo.put("CHECK_DEPT_NAME", dailyCheck.getDeptName());
        checkInfo.put("CHECK_DATE", dailyCheck.getCheckTime());
        checkInfo.put("TEMPLATE_NAME", dailyCheck.getTemplateName());
        //整改完成时限 获取整改信息
        List<JgRectification> rectificationList = rectificationMapper.selectByCheckId(dailyCheck.getId(), "4");
        checkInfo.put("RECTIFICATION_TIME_LIMIT", rectificationList.size() > 0 ? rectificationList.get(0).getRectificationTimeLimit() : "");
        //其他问题
        checkInfo.put("OTHER_PROBLEM", dailyCheck.getOtherProblem());
        //监督检查要点表url
        checkInfo.put("CHECK_ITEM_TABLEURL", dailyCheck.getCheckItemTableUrl());
        //结果记录表url
        checkInfo.put("RESULT_RECORD_URL", dailyCheck.getResultRecordUrl());  //告知页
        checkInfo.put("INFORM_URL", dailyCheck.getInformUrl());
        checkInfo.put("COMANY_PIC", dailyCheck.getComanyPic());
        checkInfo.put("MANAGE_STATUS", dailyCheck.getManageStatus());
        checkInfo.put("MANAGE_STATUS", dailyCheck.getManageStatus());
        checkInfo.put("CHECK_TIME", dailyCheck.getCheckTime());
        checkInfo.put("userList", schemePlanUser);
        result.put("checkInfo", checkInfo);
        Map<String, Object> companyInfo = tcCompanyMapper.selectCompanyInspectionInfo(dailyCheck.getCompanyId());
        result.put("baseInfo", companyInfo);
        List<JgSchemeStandard> standardList = schemeStandardMapper.selectByCheckId(checkId);
        result.put("standardList", standardList);
        return result;

    }

    /**
     * 获取检查结果中点击检查项目的时候显示详细项列表
     *
     * @param dailyStandardId
     * @return
     */
    public List<JgSchemeContent> getCheckContentList(Long dailyStandardId) {
        return schemeContentMapper.selectByStandardId(dailyStandardId);

    }

    /**
     * 获取可关联合并的日常检查任务
     *
     * @param companyId 企业id
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public List<Map<String, Object>> getDailyMergeInspectList(Long companyId) {
        CommonSearchEntity params = new CommonSearchEntity();
        params.setUserId(UserHelper.getUserId());
        params.setDataRange(UserHelper.getUserInfo().getDataRange());
        params.setDeptId(UserHelper.getUserInfo().getDeptId());
        List<Map<String, Object>> dailyCheckList = dailyCheckMapper.selectDailyMergeInspectList(companyId, params);
        List<Map<String, Object>> dailyCheckListResult = dailyCheckList.stream().filter(daily -> {
            //如果检查id是空的说明现在应该检查的日常检查还未进行检查，如果检查id存在说明当前已经检查，如果状态是3的才是未检查完成的
            return daily.get("CHECK_ID") == null || (daily.get("CHECK_ID") != null && "3".equals(daily.get("CHECK_STAT") + ""));
        }).collect(Collectors.toList());
        TcCompany company = tcCompanyMapper.selectById(companyId);
        List<Map<String, Object>> resultList = new ArrayList<>();
        for (Map<String, Object> stringObjectMap : dailyCheckListResult) {
            JgDailyCheck dailyCheck = null;
            if (stringObjectMap.get("CHECK_ID") == null) {
                //如果当前日常检查还未创建，那么创建一个日常检查单，
                dailyCheck = dailyInspectService.createDailyCheck(company, Integer.parseInt(stringObjectMap.get("CHECK_NUM") + ""), false);

            } else {
                dailyCheck = dailyCheckMapper.selectById(Long.parseLong(stringObjectMap.get("CHECK_ID") + ""));
            }
            Map<String, Object> resultMap = new HashMap<>();
            resultMap.put("ID", dailyCheck.getId());
            resultMap.put("TASK_NAME", "第" + stringObjectMap.get("CHECK_NUM") + "次日常检查任务");
            resultList.add(resultMap);
        }
        return resultList;
    }
}
